<template>
  <div class="page-content">
    <!--    头部-->
    <div class="table_bar">
      <el-date-picker
        class="flex-item"
        v-model="value2"
        type="date"
        placeholder="开始日期"
        style="width: 130px; margin: 0 6px 6px 0"
      />
      <el-date-picker
        class="flex-item"
        v-model="value2"
        type="date"
        placeholder="结束日期"
        style="width: 130px; margin: 0 6px 6px 0"
      />
      <el-select
        v-model="status"
        class="flex-item"
        placeholder="状态"
        style="width: 150px; margin: 0 6px 6px 0"
      >
        <el-option
          class="flex-item"
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-input placeholder="搜索" style="width: 200px; margin: 0 6px 6px 0" />

      <el-button>查询</el-button>
      <el-button type="success" @click="dialogFormVisible = true">新增</el-button>
      <el-button type="danger">删除</el-button>
      <el-button type="info">导出</el-button>
    </div>
    <!--    表格-->
    <el-table
      ref="multipleTableRef"
      :data="tableData"
      :header-cell-style="{ 'text-align': 'center' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column fixed type="selection" :selectable="selectable" width="45" />
      <el-table-column fixed prop="travelDate" label="出差时间" width="120"></el-table-column>
      <el-table-column property="customerName" label="客户名称(全称)" width="250" />
      <el-table-column
        property="location"
        label="地点"
        width="90"
        show-overflow-tooltip
        align="center"
      />
      <el-table-column property="machineModel" label="机型" align="center" />
      <el-table-column property="serviceType" label="服务类型" align="center" />
      <el-table-column label="状态" align="center" width="100">
        <!-- 作用域插槽 -->
        <template #default="scope">
          <el-button
            size="small"
            :type="
              scope.row.isApprove == 0
                ? 'primary'
                : scope.row.isApprove == 1
                  ? 'info'
                  : scope.row.isApprove == 2
                    ? 'success'
                    : 'danger'
            "
            plain
            >{{
              scope.row.isApprove == 0
                ? '未提交'
                : scope.row.isApprove == 1
                  ? '审核中'
                  : scope.row.isApprove == 2
                    ? '已通过'
                    : '未通过'
            }}</el-button
          >
        </template>
        <!--        <el-button size="small" type="success" plain>未导出</el-button>-->
      </el-table-column>
      <el-table-column label="操作" width="250" align="center">
        <template #default="scope">
          <el-button type="primary" @click="travelDetail(scope.row.id)">详情</el-button>
          <el-button type="danger" @click="delTravel(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页-->
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="currentPage2"
        v-model:page-size="pageSize2"
        :page-sizes="[10, 20, 30]"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 对话框  -->
    <el-dialog v-model="dialogFormVisible" title="新增差旅信息" width="500" center>
      <el-form :model="form" label-width="auto" ref="formRef">
        <el-form-item label="出差日期">
          <el-date-picker
            v-model="selectedDate"
            type="date"
            placeholder="选择日期"
            :disabled-date="disabledDate"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="form.customerName" autocomplete="off" placeholder="客户名称全称" />
        </el-form-item>
        <el-form-item label="地点">
          <el-input v-model="form.location" autocomplete="off" placeholder="省份/直辖市" />
        </el-form-item>
        <el-form-item label="机型">
          <el-select v-model="form.machineModel" placeholder="选择机型">
            <el-option label="大PONY" value="大PONY" />
            <el-option label="小PONY" value="小PONY" />
            <el-option label="单边桥" value="单边桥" />
            <el-option label="小龙门" value="小龙门" />
            <el-option label="大龙门" value="大龙门" />
            <el-option label="非标项目" value="非标项目" />
            <el-option label="303-IOTA" value="303-IOTA" />
            <el-option label="303-PEAL" value="303-PEAL" />
            <el-option label="303其他" value="303其他" />
            <el-option label="HMQ-Global" value="HMQ-Global" />
            <el-option label="HMQ-Explorer/Inspector" value="HMQ-Explorer/Inspector" />
            <el-option label="HMQ-龙门" value="HMQ-龙门" />
            <el-option label="HMQ-其他" value="HMQ-其他" />
            <el-option label="其他厂家" value="其他厂家" />
          </el-select>
        </el-form-item>
        <el-form-item label="服务类型">
          <el-select v-model="form.serviceType" placeholder="选择服务类型">
            <el-option label="售前支持" value="售前支持" />
            <el-option label="新机交付" value="新机交付" />
            <el-option label="有偿维修" value="有偿维修" />
            <el-option label="有偿培训" value="有偿培训" />
            <el-option label="检调" value="检调" />
            <el-option label="大修" value="大修" />
            <el-option label="改造" value="改造" />
            <el-option label="搬迁" value="搬迁" />
            <el-option label="保修" value="保修" />
            <el-option label="维保" value="维保" />
            <el-option label="免费服务" value="免费服务" />
            <el-option label="新机销售" value="新机销售" />
            <el-option label="非标销售" value="非标销售" />
            <el-option label="售后市场" value="售后市场" />
            <el-option label="客户回访" value="客户回访" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <template v-for="(value, item, index) in travelList" :key="index">
          <el-form-item :label="item">
            <el-input v-model.number="formFields[value]" type="number"></el-input>
          </el-form-item>
        </template>
        <el-form-item label="其他差旅项目">
          <el-switch v-model="showOther" />
        </el-form-item>
        <el-form-item label="自驾起止(从...到...)">
          <el-input v-model="form.selfDriving" placeholder="自驾起止(从...到...)" />
        </el-form-item>
        <el-form-item label="补助类型">
          <el-select v-model="form.subsidyType" placeholder="补助类型">
            <el-option label="正常补助" value="正常补助" />
            <el-option label="两人出差" value="两人出差" />
            <el-option label="路途_100" value="路途_100" />
            <el-option label="路途_200" value="路途_200" />
            <el-option label="当日往返_100" value="当日往返_100" />
            <el-option label="当日往返_200" value="当日往返_200" />
            <el-option label="定额_200" value="定额_200" />
            <el-option label="特殊_300" value="特殊_300" />
            <el-option label="特殊_500" value="特殊_500" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.note" placeholder="备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="sendTravelForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="showOther" width="500">
      <el-checkbox-group v-model="checkList">
        <el-checkbox label="飞机" value="飞机" />
        <el-checkbox label="火车" value="火车" />
        <el-checkbox label="公共交通" value="公共交通" />
        <el-checkbox label="出租" value="出租" />
        <el-checkbox label="住宿" value="住宿" />
        <el-checkbox label="招待费" value="招待费" />
        <el-checkbox label="通讯费" value="通讯费" />
        <el-checkbox label="邮寄费" value="邮寄费" />
        <el-checkbox label="车补里程" value="车补里程" />
        <el-checkbox label="高速费" value="高速费" />
        <el-checkbox label="停车费" value="停车费" />
        <el-checkbox label="其他" value="其他" />
      </el-checkbox-group>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="showOther = false">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
  import { ref, onMounted, computed } from 'vue'
  import { TravelService } from '@/api/travelApi'
  import { ComponentSize, ElForm, ElMessage, TableInstance } from 'element-plus'
  import EmojiText from '@/utils/emojo'
  import { formatUTC } from '@/utils/format'
  import { ApiStatus } from '@/utils/http/status'

  const value2 = ref('')
  const currentPage2 = ref(5)
  const size = ref<ComponentSize>('default')
  const background = ref(false)
  const disabled = ref(false)
  const pageSize2 = ref(1)
  const selectedDate = ref('')
  const status = ref('')
  const options = [
    {
      value: '未提交',
      label: '未提交'
    },
    {
      value: '审核中',
      label: '审核中'
    },
    {
      value: '已通过',
      label: '已通过'
    },
    {
      value: '未通过',
      label: '未通过'
    }
  ]
  const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
  }
  const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
  }

  const multipleTableRef = ref<TableInstance>()
  const multipleSelection = ref<any[]>([])
  const dialogFormVisible = ref(false)
  /*const toggleSelection = (rows?: any[], ignoreSelectable?: boolean) => {
    if (rows) {
      rows.forEach((row) => {
        multipleTableRef.value!.toggleRowSelection(row, undefined, ignoreSelectable)
      })
    } else {
      multipleTableRef.value!.clearSelection()
    }
  }*/
  const handleSelectionChange = (val: any[]) => {
    multipleSelection.value = val
  }
  interface FormType {
    userName?: string
    travelDate: string
    customerName: string
    location: string
    machineModel: string
    serviceType: string
    airplane?: number
    train?: number
    busAndMetro?: number
    hotel?: number
    selfDriving?: string
    other?: string
    taxi?: number
    communication?: number
    entertain?: number
    postage?: number
    vehicleSupplement?: number
    highWay?: number
    parkFee?: number
    subsidyType?: string
    travelAllowance?: number
    note: string
    isApprove: number
  }
  const form: FormType = reactive({
    userName: '徐世权',
    travelDate: '',
    customerName: '',
    location: '',
    machineModel: '',
    serviceType: '',
    selfDriving: '',
    note: ''
  })
  const selectable = (row: FormType) => {
    console.log(row)
    return ![1, 2].includes(row.isApprove)
  }
  const showOther = ref(false)
  const checkList = ref([])
  const travelList = computed(() => {
    // 使用 reduce 方法来构建一个对象，其中键是 checkList 中的元素，值是任意的（这里我们设置为 true）
    return checkList.value.reduce(
      (acc, item) => {
        switch (item) {
          case '飞机':
            acc[item] = 'airplane'
            break
          case '火车':
            acc[item] = 'train'
            break
          case '公共交通':
            acc[item] = 'busAndMetro'
            break
          case '出租':
            acc[item] = 'taxi'
            break
          case '住宿':
            acc[item] = 'hotel'
            break
          case '通讯费':
            acc[item] = 'communication'
            break
          case '招待费':
            acc[item] = 'entertain'
            break
          case '邮寄费':
            acc[item] = 'postage'
            break
          case '车补里程':
            acc[item] = 'vehicleSupplement'
            break
          case '高速费':
            acc[item] = 'highWay'
            break
          case '停车费':
            acc[item] = 'parkFee'
            break
          case '其他':
            acc[item] = 'other'
            break
        }
        return acc
      },
      {} as Record<string, string>
    )
  })
  const formFields = computed({
    get: () => form,
    set: (value: any, key: any) => {
      form[key] = value
    }
  })

  const params = {
    pageNum: 1,
    pageSize: 10,
    name: '徐世权',
    startDate: '',
    endDate: '',
    status: '',
    search: ''
  }

  const tableData: any = ref([])
  const total = ref(0)
  //重置form表单
  const formRef = ref<InstanceType<typeof ElForm>>()

  const sendTravelForm = async () => {
    try {
      form.travelDate = formatUTC(selectedDate.value)
      const res = await TravelService.addTravel(form)
      if (res.code === ApiStatus.success) {
        ElMessage.success(`添加成功 ${EmojiText[200]}`)
        dialogFormVisible.value = false
        formRef.value?.resetFields()
        addArticle()
      }
    } catch (err) {
      console.error(err)
    }
  }
  // 获取列表
  const addArticle = async () => {
    try {
      const res = await TravelService.getTravelList(params)
      if (res.code === 0) {
        console.log(res)
        tableData.value = res.rows
        total.value = res.total
        ElMessage.success(`获取成功 ${EmojiText[200]}`)
      }
    } catch (err) {
      console.error(err)
    }
  }
  // 时间选择器
  const disabledDate = (time: Date) => {
    const today = new Date()
    const oneDay = 24 * 60 * 60 * 1000 // 一天的毫秒数
    const targetDate = new Date(today.getTime() - oneDay * 3) // 三天前

    return time.getTime() < targetDate.getTime() || time.getTime() > today.getTime()
  }
  //获取差旅详情
  const travelDetail = async (id: number) => {
    try {
      const res = await TravelService.getTravelDetail(id)
      if (res.code === ApiStatus.success) {
        console.log(res.data)
      }
    } catch (err) {
      console.error(err)
    }
  }
  //删除差旅信息
  const delTravel = async (params: number) => {
    try {
      let arr: number[] = [params]
      const res = await TravelService.delTravel(arr)
      if (res.code === ApiStatus.success) {
        console.log(res)
      }
    } catch (err) {
      console.error(err)
    }
  }
  onMounted(() => {
    addArticle()
    // 监听 travelList 的变化
    watch(
      travelList,
      (newObj, oldObj) => {
        // 处理新增的项
        for (const [key, value] of Object.entries(newObj)) {
          if (!oldObj.hasOwnProperty(key)) {
            form[value] = 0
          }
        }

        // 处理删除的项
        for (const [key, value] of Object.entries(oldObj)) {
          if (!newObj.hasOwnProperty(key)) {
            delete form[value]
          }
        }
      },
      { deep: true }
    )
  })
</script>
<style lang="scss" scoped>
  .table-bar {
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    box-sizing: border-box;
    .flex-item {
      flex: 1 1 200px;
      min-width: 150px;
      box-sizing: border-box;
    }
  }
  .el-button {
    margin: 0 6px 6px 0 !important;
  }
  .demo-pagination-block {
    margin: 10px 0 0 10px;
    display: flex;
    justify-content: end;
    align-items: center;
  }
</style>
